
import { useEffect, useState, useContext } from 'react'
import { PageContext } from '@/store/pageContext';

import { Popover } from '@arco-design/web-react';
import { IconDelete, IconEye, IconEyeInvisible } from '@arco-design/web-react/icon';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';


function BlcokCardAction({ display, onChange }) {

  function handleClick(e) {
    //阻止冒泡
    e.stopPropagation(); //阻止原生事件冒泡
    e.nativeEvent.stopImmediatePropagation(); //阻止最外层document上的事件冒泡
  }

  return <span className='text-base flex gap-2' onClick={handleClick}>
    <IconDelete onClick={() => { onChange('del') }} />
    {display ? <IconEyeInvisible onClick={() => { onChange('display') }} /> : <IconEye onClick={() => { onChange('display') }} />}
  </span>
}

// 积木卡片
function BlcokCard({ icon, name, display, action = false, onClick, onActionChange }) {
  function setClassName(icon) {
    return icon ? `oem-icon ${icon}` : 'oem-icon icon-guiyinmuxing'
  }

  return <div onClick={onClick} className={`p-2 flex justify-between cursor-pointer hover:bg-slate-100 rounded-md  ${action && !display ? "opacity-20" : ""}`} >
    <div className='flex items-center gap-2 justify-between w-full '>
      <i className={setClassName(icon)}></i>
      <span className='flex-1'>{name}</span>
      {
        action && <BlcokCardAction onChange={onActionChange} display={display} />
      }
    </div>
  </div>
}

// 所有积木块
function BlockCardAll({ onChange }) {

  const [allBlock, setAllBlock] = useState([])

  useEffect(() => {
    fetch(`http://localhost:3030/api/themeAll`, {
      method: "GET",
      headers: {
        'Content-Type': 'application/json',
      }
    }).then(data => data.json()).then(({ data }) => {
      setAllBlock(data)
    });
  }, [])

  function handleAddBlock(key, key2) {

    const currentBlockConf = JSON.parse(JSON.stringify(allBlock[key][key2]));
    currentBlockConf['display'] = true;
    onChange(currentBlockConf)
  }

  return <div className='w-40'>
    {
      Object.keys(allBlock).map((key, index) => {
        return <div key={index} >
          <div className='text-gray-500'>{key}</div>
          {
            Object.keys(allBlock[key]).map((item, idx) => <BlcokCard onClick={() => handleAddBlock(key, item)} key={idx} name={item}></BlcokCard>)
          }
        </div>
      })
    }

  </div>
}

// 添加积木块
function AddBlockCard({themeId}) {
  const { dispatch } = useContext(PageContext);

  function handleAddBlock(block) {
    block['id'] = new Date().getTime() + Math.floor((Math.random() * 100) + 1) + '';
    dispatch({ type: "add", data: block,themeId })
  }
  return <Popover
    trigger='click'
    unmountOnExit={false}
    content={<BlockCardAll onChange={handleAddBlock} />}
  >
    <BlcokCard name='添加积木' icon='icon-Picture_delete'></BlcokCard>
  </Popover>

}


export default function PageMenu({ value, onchange, themeId }) {

  const { state, dispatch } = useContext(PageContext);

  function handleActionChange(item, index, type) {
    dispatch({ type: type, id: item.id, index: index, data: item, themeId:themeId })
  }


  const onDragEnd = (result) => {
    if (!result.destination) {
      return;
    }
    dispatch({ type: "move", toIndex: result.destination.index, id: state[result.source.index].id, startIndex: result.source.index, themeId:themeId })
  };




  return <div className='py-3'>
    <div className='flex flex-col'>

      <DragDropContext onDragEnd={onDragEnd}>
        <Droppable droppableId="droppable">
          {(provided, snapshot) => {
            return (
              <div
                {...provided.droppableProps}
                ref={provided.innerRef}
                className='overflow-auto'
              >
                {state.map((item, index) => (
                  <Draggable key={item.id} draggableId={item.id} index={index}>
                    {(provided, snapshot) => (
                      <div
                        className={`${value == item.id ? "bg-slate-100" : ""}`}
                        ref={provided.innerRef}
                        {...provided.draggableProps}
                        {...provided.dragHandleProps}
                      >
                        <BlcokCard key={item.id} action={true} onActionChange={handleActionChange?.bind(null, item, index)} onClick={onchange?.bind(null, item, index)} name={item.router} display={item.display} icon={item.icon}></BlcokCard>
                      </div>
                    )}
                  </Draggable>
                ))}
                {provided.placeholder}
              </div>
            );
          }}
        </Droppable>
      </DragDropContext>
      <AddBlockCard themeId={themeId} />
    </div>
  </div>
}

    //  {/* {state.map((item, index) => {
    //               return <BlcokCard key={item.id} action={true} onActionChange={handleActionChange?.bind(null, item, index)} onClick={onchange?.bind(null, item, index)} name={item.router} display={item.display} icon={item.icon}></BlcokCard>
    //             })} */}